<template>
  <div class="main">
    <div class="top">
      <div class="breadcrumb">
        <p class="toptitle">首页</p>
        <i class="iconfont icon-youjiantou"></i>
        <p class="toptitle">商品管理</p>
        <i class="iconfont icon-youjiantou"></i>
        <p class="lasttitle">商品编辑</p>
      </div>
      <Welcome></Welcome>
    </div>
    <div class="table">
      <p class="list">商品添加</p>

      <el-form-item label="商品名称">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="商品分类">
        <el-select v-model="form.category" placeholder="请选择商品分类">
          <el-option v-for="item in options" :key="item.id" :label="item.cateName" :value="item.cateName"  :disabled="item.state === 0" />
        </el-select>
      </el-form-item>

      <el-form-item label="商品价格">
        <el-input-number v-model="form.price" :min="1" :max="10" @change="handleChange" />
      </el-form-item>

      <el-form-item label="商品图片">
        <el-upload class="avatar-uploader" action="/api/goods/goods_img_upload"
          :show-file-list="false" :on-success="handleAvatarSuccess"  :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品描述">
        <el-input autosize type="textarea" v-model="form.goodsDesc" placeholder="请填写商品描述" />
      </el-form-item>

      <el-button type="primary" class="button" @click="onSubmit">修改商品</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { getcategory, updateGoods } from "../../api/account"
import { useRoute } from 'vue-router'
import {serverUrl} from '../../utils/commen'
import Welcome from '../../components/Welcome.vue'

const route = useRoute(); // 获取路由对象
const form = reactive({
  id: 0,
  name: '',
  price: 0,
  imgUrl: '',
  category: '',
  goodsDesc: ''
});

const options = ref([]);

const getcate = async (pagedata) => {
  const data = await getcategory(pagedata);
  console.log(data);
  options.value = data.data;
  console.log(options.value);
};

const imageUrl = ref('');
const handleAvatarSuccess = (response, uploadFile) => {
  console.log('Upload response:', response); // 打印上传接口返回的响应
  if (response.code === 0) {
    const imgUrl = serverUrl + response.imgUrl;
    imageUrl.value = imgUrl;
    // 只存储图片的文件名
    form.imgUrl = imgUrl.split('/').pop(); // 获取最后一部分作为文件名
    ElMessage.success(response.msg); // 显示成功消息
  } else {
    ElMessage.error(response.msg); // 显示错误消息
  }
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type!== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!');
    return false;
  }
  return true;
};

// 修改商品
const editgoods = async (form) => {
  const data = await updateGoods(form);
  if (data.code === 0) {
    ElMessage.success('修改成功');
  }
}

const onSubmit = () => {
  // 进行表单验证
  if (!form.name || form.price === 0 ||!form.category ||!form.goodsDesc) {
    ElMessage.error('请填写完整的商品信息');
    return;
  }
  editgoods(form);
}

onMounted(async () => {
  // 从路由查询参数中获取商品信息并赋值到表单
  const query = route.query;
  if (query.id) {
    form.id = Number(query.id);
    form.name = query.name || '';
    form.price = Number(query.price) || 0;
    form.imgUrl = query.imgUrl || '';
    form.category = query.category || '';
    form.goodsDesc = query.goodsDesc || '';
    imageUrl.value = form.imgUrl; // 同时赋值给 imageUrl
  }

  const pagedata = reactive({
    currentPage: 1,
    pageSize: 1000,
  });

  await getcate(pagedata);
})
</script>

<style scoped>
.main {
  width: 100%;
  height: 70px;
  background-color: #f0f0f0;
}

/* 中间 */
.table {
  margin: 20px;
  padding: 20px;
  border-radius: 5px;
  background-color: #fff;
  min-height: 600px;
}

.list {
  width: 100%;
  border-bottom: 1px solid #e1e1e1;
  font-size: 20px;
  margin-bottom: 20px;
  padding-bottom: 10px;
}

/* 顶部面包屑 */
.toptitle {
  font-weight: bold;
}

.top {
    width: 96%;
    height: 50px;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    /* 内容分布在左右两侧 */
    padding: 0 20px;
    /* 添加左右内边距 */
}

.breadcrumb {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.iconfont {
  font-size: 14px;
  color: #999999;
  margin: 0 5px;
}

.lasttitle {
  color: #999999;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.button {
  margin-left: 20px;
}
</style>    